﻿using FreeSql;
using Rougamo;
using Rougamo.Context;
using System.Data;



[AttributeUsage(AttributeTargets.Method)]
public class TransactionalAttribute : MoAttribute
{
    /// <summary>
    /// 级别
    /// </summary>
    public Propagation Propagation { get; set; } = Propagation.Required;
    /// <summary>
    /// 
    /// </summary>
    public IsolationLevel IsolationLevel { get; set; } = IsolationLevel.ReadCommitted;



    IUnitOfWork _uow;
    public override void OnEntry(MethodContext context)
    {
        var uowManager = context.GetService<UnitOfWorkManager>() ?? throw new Exception("UnitOfWorkManager 实例失败");
        _uow = uowManager.Begin(this.Propagation, this.IsolationLevel);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="arg"></param>
    public override void OnException(MethodContext arg)
    {
        _uow.Rollback();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void OnExit(MethodContext context)
    {
        try
        {
            //返回值是正常提交 
            if (context.Exception == null)
            {
                object? o = context.ReturnValue;
                if (o != null && o is ResultDTO res && !res.Success)
                {
                    _uow.Rollback();
                }
                else
                {
                    _uow.Commit();
                }
            }
        }
        finally
        {
            _uow.Dispose();
        }

    }
}
